package com.gking.aiService.utils.commonUtil;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

/**
 * 对数据进行序列化和反序列化
 */

public class JsonUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 序列化对象为 JSON 字符串
    public static <T> String serialize(T object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 反序列化 JSON 字符串为对象
    public static <T> T deserialize(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 序列化数组为 JSON 字符串
    public static <T> String serializeArray(T[] array) {
        try {
            return objectMapper.writeValueAsString(array);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 反序列化 JSON 字符串为数组
    public static <T> T[] deserializeArray(String json, Class<T[]> arrayClass) {
        try {
            return objectMapper.readValue(json, arrayClass);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 序列化列表为 JSON 字符串
    public static <T> String serializeList(List<T> list) {
        try {
            return objectMapper.writeValueAsString(list);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 反序列化 JSON 字符串为列表
    public static <T> List<T> deserializeList(String json, TypeReference<List<T>> typeReference) {
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}